package com.ylq.reggie_take_away.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ylq.reggie_take_away.common.R;
import com.ylq.reggie_take_away.entity.Category;
import com.ylq.reggie_take_away.service.CategoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {

    private static final Logger log = LoggerFactory.getLogger(CategoryController.class);
    @Autowired
    public CategoryService categoryService;

    @PostMapping
    public R<String> saveCategory(@RequestBody Category category) {
        log.info("category: {}", category);
        categoryService.save(category);
        return R.success("新增分类成功");
    }

    @GetMapping("/page")
    public R<Page> page(int page,int pageSize) {
        log.info("page: {}, pageSize:{}", page,pageSize);

        Page<Category> pageInfo = new Page<>();

        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.orderByAsc(Category::getSort);

        categoryService.page(pageInfo, queryWrapper);

        return R.success(pageInfo);
    }

    @DeleteMapping
    public R<String> deleteCategory(Long ids) {

        log.info("删除category,id为: {}", ids);
        //remove方法写在实现类中，做了菜品套餐关联判断
        categoryService.remove(ids);
        return R.success("分类信息删除成功");
    }

    /**
     * 修改菜品分类
     * @param category
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Category category) {
        log.info("category: {}", category);
        categoryService.updateById(category);
        return R.success("成功");
    }

    @GetMapping("/list")
    public R<List<Category>> list(Category category){
        log.info("category: {}", category);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件
        queryWrapper.eq(category.getType()!=null,Category::getType, category.getType());
        //添加排序条件
        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        List<Category> list = categoryService.list(queryWrapper);

        return R.success(list);
    }
}
